<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/9/13
 * Time: 上午11:10
 */

namespace Admin\Ims\Controllers;

use Admin\Models\ims\XHImsBoxIn;
use Admin\Models\ims\XHImsBoxOut;
use Admin\Models\ims\XHImsProdIn;
use Admin\Models\ims\XHImsProdOut;
use Admin\Models\ims\XHImsProdType;
use Admin\Models\ims\XHImsProduct;
use Admin\Models\ims\XHsysDeviceStore;
use Admin\Models\crm\XhcustInfo;
use Helpers\Assets;
use Admin\Models\sys\XhsysEnum;

class MoblieController extends ControllerBase
{
    public function indexAction(){

    }

    public function isSingle($name){
        $single  = ['个','只','张','瓶','支','台','包'];
        $total   = ['箱','袋','盒','条'];
        if(in_array($name,$total)){
            return false;
        }
        if(in_array($name,$single)){
            return true;
        }
    }

    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['error' => 'Page Not Found']);
    }

    /**
     * 入库界面
     * created by dale 2017/9/13
     */
    public function BoxInAction()
    {
//        $this->view->setTemplateBefore('commonMoblie');
        Assets::easyUIMobile();
        $this->view->pick('moblie/BoxIn');
        Assets::importJs('js/moblie/BoxIn.js');
        $types = XHImsProdType::find([
            'columns' => 'iTypeId,sTypeName',
            'conditions' => 'bDelete=0',
        ]);
        $types = array_column($types->toArray(), 'sTypeName', 'iTypeId');
        $this->view->setVars([
            'types' => $types,
        ]);
    }

    /**
     * 获取商品枚举
     * @return string
     * created by dale 2017/9/13
     */
    public function getProdsAction()
    {
        $id = $this->request->getQuery('id', 'string');
        $prods = XHImsProduct::find([
            'columns' => 'iProdId,sProdName',
            'conditions' => 'bDelete=0 AND iTypeId=:iTypeId:',
            'bind' => ['iTypeId' => $id],
        ]);
        $prods = $prods->toArray();
        return json_encode($prods);
    }

    /**
     * 获取度量枚举
     *
     * @return string
     * created by dale 2017/9/13
     */
    public function getMeasueAction()
    {
        $id = $this->request->getQuery('iProdId', 'string');
        $prod = XHImsProduct::findFirst([
            'conditions' => 'bDelete=0 AND iProdId=:iProdId:',
            'bind' => ['iProdId' => $id],
        ]);
        $mesures = explode('/', $prod->sMeasures);
        $items = [];
        foreach ($mesures as $mesure) {
            $item['id'] = $mesure;
            $item['text'] = $mesure;
            $item['num'] = $prod->iDefNum;
            $item['measureType'] = $prod->sMeasures;
            $items[] = $item;
        }
        return json_encode($items);
    }

    /**
     * 保存入库
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/9/13
     */
    public function saveInAction()
    {
        $this->view->disable();
        $numType = $this->request->getPost('sMeasure', 'string');

        if (!$this->isSingle($numType)) {
            $obj = new XHImsBoxIn();
        } else {
            $obj = new XHImsProdIn();
            $sboxCode = $this->request->getPost('sBoxCode', 'string');
            if (isset($sboxCode)) {
                $box = XHImsBoxIn::findFirst([
                    'conditions' => 'bDelete=0 AND sBoxCode=:sBoxCode:',
                    'bind' => ['sBoxCode' => $sboxCode],
                ])->toArray();
                $obj->iBoxId = $box['iBoxId'];
            }
        }
        $obj->assign($this->request->getPost());

        if (!$this->isSingle($numType)) {
            if ($this->checkBox($this->request->getPost('sBoxCode'))) {
                return $this->sendErrorResponse(500, $numType . '入库失败,物品码重复');
            }
        } else {
            if ($this->checkPord($this->request->getPost('sProdCode'))) {
                return $this->sendErrorResponse(500, $numType . '入库失败,物品码重复');
            }
        }
        $obj->iLeftNum = $obj->iProdNum;
        $res = $obj->save();
        if ($res) {
            if ($numType != '箱' &&$numType != '袋') {
                $this->saveDevStore($this->request->getPost('sProdCode','string'));
            }
            return $this->sendSuccessResponse($numType . '入库成功');
        } else {
            return $this->sendErrorResponse(500, $numType . '入库失败');
        }
    }

    /**
     * 保存到设备库
     *
     * @param $code
     * @return bool
     *
     * created by dale 2017/11/29
     */
    public function saveDevStore($code){
        $obj   = new XHsysDeviceStore();
        $check = XHsysDeviceStore::findFirst([
            'conditions' => 'bDelete = 0 AND sDeviceNumber = :sDeviceNumber:',
            'bind'       => ['sDeviceNumber'=>$code]
        ]);
        if($check){
            return false;
        }
        $obj->sDeviceNumber = $code;
        $res = $obj->save();
        return $res;
    }

    /**
     * 检查箱码是否重复
     * @param $name
     * @return bool
     * created by dale 2017/9/14
     */
    public function checkBox($name)
    {
        $box = XHImsBoxIn::findFirst([
            'conditions' => 'bDelete=0 AND sBoxCode=:sBoxCode:',
            'bind' => ['sBoxCode' => $name]
        ]);
        if ($box) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查只吗是否重复
     * @param $name
     * @return bool
     * created by dale 2017/9/14
     */
    public function checkPord($name)
    {
        $prod = XHImsProdIn::findFirst([
            'conditions' => 'bDelete=0 AND sProdCode=:sProdCode:',
            'bind' => ['sProdCode' => $name]
        ]);
        if ($prod) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 获取总数
     *
     * @return string
     * created by dale 2017/9/13
     */
    public function getTotalAction()
    {
        $time = time();
        $nowDay = date('Y-m-d', $time);
        $secondDay = date('Y-m-d', $time + 86400);
        $prodNums = XHImsProdIn::find([
            'conditions' => 'bDelete=0 AND tCreateDate>=:nowDay:AND tCreateDate<=:secondDay: AND iBoxId is null',
            'bind' => ['nowDay' => $nowDay, 'secondDay' => $secondDay],
        ]);
        $prodNums = count($prodNums);
        $boxs = XHImsBoxIn::find([
            'columns' => 'SUM(iProdNum) as prodNums,COUNT(iBoxId) as boxNums',
            'conditions' => 'bDelete=0 AND tCreateDate>=:nowDay:AND tCreateDate<=:secondDay:',
            'bind' => ['nowDay' => $nowDay, 'secondDay' => $secondDay],
        ]);
        $boxs = $boxs->toArray();
        $prodNums += intval($boxs[0]['prodNums']);
        $boxNums = intval($boxs[0]['boxNums']);
        $nowDStr = date('Y/m/d', time());
        $str = '合计(' . $nowDStr . ')&nbsp;: &nbsp; <font color="#ff8c00">' . $boxNums . '/' . $prodNums . '</font>';
        return $str;
    }

    /**
     * 出库界面
     * created by dale 2017/9/13
     */
    public function BoxOutAction()
    {
        Assets::easyUIMobile();
//        $this->view->setTemplateBefore('commonMoblie');

        $this->view->pick('moblie/boxOut');
        Assets::importJs('js/moblie/BoxOut.js');

        $schools = XhcustInfo::find([
            'columns' => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete=0 AND iSchoolId is not null'
        ]);
        $schools = array_column($schools->toArray(), 'sSchoolName', 'iSchoolId');
        $sYear = [];
        $year = intval(date('Y', time()));
        for ($i = 0; $i < 6; $i++) {
            $sYear[$year] = $year;
            $year--;
        }
        $this->view->setVars([
            'schools' => $schools,
            'iChargeMode' => XhsysEnum::getEnumByNodeName('收费模式'),
            'sYear' => $sYear
        ]);
    }





    /**
     * 保存出库
     * created by dale 2017/9/14
     */
    public function saveOutAction()
    {
        $this->view->disable();
        $time = date('Y/m/d', time());
        $numType = $this->request->getPost('sMeasure', 'string');
        $iProdId = $this->request->getPost('iProdId', 'string');
        $iTypeId = $this->request->getPost('iTypeId', 'string');
        $iOutNum = $this->request->getPost('iOutNum', 'string');
        if ($numType == '箱' || $numType == '袋') {
            $code = $this->request->getPost('code', 'string') OR die('缺少参数');
            $check = XHImsBoxIn::findFirst([
                'conditions' => 'bDelete=0 AND iProdId=:iProdId: AND iTypeId=:iTypeId: AND  sBoxCode=:sBoxCode: AND iState=:iState:',
                'bind' => ['iProdId' => $iProdId, 'iTypeId' => $iTypeId, 'sBoxCode' => $code, 'iState' => 1],
            ]);
            $obj = new XHImsBoxOut();
        } else {
            $code = $this->request->getPost('code', 'string') OR die('缺少参数');
            $check = XHImsProdIn::findFirst([
                'conditions' => 'bDelete=0 AND iProdId=:iProdId: AND iTypeId=:iTypeId: AND  sProdCode=:sProdCode: AND iState=:iState:',
                'bind' => ['iProdId' => $iProdId, 'iTypeId' => $iTypeId, 'sProdCode' => $code, 'iState' => 1],
            ]);
            $obj = new XHImsProdOut();
        }
        if (!$check) {
            return $this->sendErrorResponse(500, $numType . '码不存在或者改货物已经出库');
        } else {
            if ($numType == '箱' || $numType == '袋') {
                $check->iLeftNum = $check->iLeftNum - $iOutNum;
                if ($check->iLeftNum == 0) { //全部出库
                    $check->iState = 2;
                    if ($check->sRemark != null) { //记录
                        $check->sRemark .= $time . '出库' . $iOutNum . ',全部出库。';
                    } else {
                        $check->sRemark = $time . '出库' . $iOutNum . ',全部出库。';
                    }
                } else {
                    if ($check->sRemark != null) { //记录
                        $check->sRemark .= $time . '出库' . $iOutNum . ',';
                    } else {
                        $check->sRemark = $time . '出库' . $iOutNum . ',';
                    }
                }
            } else {
                $check->iState = 2;
            }
            $check->save(); //保存入库表出库信息
        }
        $obj->assign($this->request->getPost());
        $obj->sYear = $this->request->getPost('sYear') == '' ? null : $this->request->getPost('sYear');
        $obj->iChargeMode = $this->request->getPost('iChargeMode') == '' ? null : $this->request->getPost('iChargeMode');
        if ($numType == '箱' || $numType == '袋') {
            $obj->iBoxId = $check->iBoxId;
            if ($check->iProdNum == $iOutNum) { //如果总数与出库相等
                $obj->iType = 1;
            } else {  //部分出库
                $obj->iType = 2;
            }
        } else {
            $obj->sProdCode = $code;
            $obj->iType = 1;
            $obj->iBoxId = $check->iBoxId;
        }
        $res = $obj->save();
        if ($res) {
            if($numType != '箱' && $numType != '袋' && $check->iBoxId != null){ //箱盒内出库
                $pordBox = XHImsBoxIn::findFirst($check->iBoxId);
                $pordBox->iLeftNum -=1;
                $pordBox->save();
            }
            return $this->sendSuccessResponse($numType . '出库成功');
        } else {
            return $this->sendErrorResponse(500, $numType . '出库失败');
        }
    }

    public function getLeftNumAction()
    {
        $code = $this->request->getPost('code', 'string');
        $obj = XHImsBoxIn::findFirst([
            'conditions' => 'bDelete=0 AND sBoxCode=:sBoxCode:',
            'bind' => ['sBoxCode' => $code],
        ]);
        if ($obj) {
            return $this->sendJsonResponse(['leftNum' => $obj->iLeftNum]);
        } else {
            return $this->sendJsonResponse(['leftNum' => '']);
        }
    }

    /**
     * 明细
     *
     * created by dale 2017915
     */
    public function detailAction()
    {
        Assets::easyUIMobile();
        $this->view->pick('moblie/detail');
        Assets::importJs('js/moblie/detail.js');

    }


    public function getBPInfoAction()
    {
        $code = $this->request->getPost('code') or die('缺少参数');
        $box = XHImsBoxIn::findFirst([
            'conditions' => 'bDelete=0 AND  sBoxCode=:sBoxCode: AND iState=:iState:',
            'bind' => ['sBoxCode' => $code, 'iState' => 1],
        ]);
        $danwei = 1;
        if (!$box) {
            $prod = XHImsProdIn::findFirst([
                'conditions' => 'bDelete=0 AND  sProdCode=:sProdCode: AND iState=:iState:',
                'bind' => ['sProdCode' => $code, 'iState' => 1],
            ]);
            $obj = $prod;
        } else {
            $obj = $box;
            $danwei = 2;
        }
        $prodforM = XHImsProduct::findFirst([
            'conditions' => 'bDelete=0 AND iProdId=:iProdId:',
            'bind' => ['iProdId' => $obj->iProdId],
        ]);
        $mesures = explode('/', $prodforM->sMeasures);

        $single  = ['个','只','张','瓶','支','台','包'];
        $total   = ['箱','袋','盒','条'];
        $items = [];
        foreach ($mesures as $mesure) {
            $item['id'] = $mesure;
            $item['text'] = $mesure;
            if ($danwei == 2 && in_array($mesure,$total) ) {
                $item['select'] = true;
            } else if ($danwei == 1 &&  in_array($mesure,$single)) {
                $item['select'] = true;
            } else {
                $item['select'] = false;
            }
            $items[] = $item;
        }
        if (!$obj) {
            return $this->sendErrorResponse(500, '该货物不存在');
        }
        $data = $obj->toArray();


        $prods = XHImsProduct::find([  //获取商品
            'columns' => 'iProdId,sProdName',
            'conditions' => 'bDelete=0',
        ]);
        $prods = $prods->toArray();


        $types = XHImsProdType::find([  //获取类型
            'columns' => 'iTypeId,sTypeName',
            'conditions' => 'bDelete=0',
        ]);
        $types = $types->toArray();


        $data['measure'] = $items;
        $data['type'] = $danwei;
        $data['prods'] = $prods;
        $data['prodType'] = $types;

        return $this->sendJsonResponse($data);
    }

    /**
     * 获取type类型
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017915
     */
    public function getTypeAction()
    {
        $types = XHImsProdType::find([  //获取类型
            'columns' => 'iTypeId,sTypeName',
            'conditions' => 'bDelete=0',
        ]);
        $types = $types->toArray();

        $items = [];
        foreach ($types as $type) {
            $item['id'] = $type['iTypeId'];
            $item['text'] = $type['sTypeName'];
            $items[] = $item;
        }

        return $this->sendJsonResponse($items);
    }

    /**
     * 箱盒内货物出库
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017915
     */
    public function saveOutInBoxAction()
    {
        $sBoxCode = $this->request->getPost('sBoxCode', 'string') or die('缺少参数');
        $code = $this->request->getPost('code', 'string') or die('缺少参数');
        $box = XHImsBoxIn::findFirst([
            'conditions' => 'bDelete=0 AND sBoxCode=:sBoxCode:',
            'bind' => ['sBoxCode' => $sBoxCode]
        ]);
        if (!$box) {
            return $this->sendErrorResponse(500, '所属箱子不存在');
        }
        $check = XHImsProdOut::findFirst([
            'conditions' => 'bDelete=0 AND sProdCode=:sProdCode:',
            'bind' => ['sProdCode' => $code],
        ]);
        if ($check) {
            return $this->sendErrorResponse(500, '该货物已出库,请不要重复扫描');
        }
        $obj = new XHImsProdOut();
        $obj->assign($this->request->getPost());
        $obj->iBoxId = $box->iBoxId;
        $obj->sProdCode = $code;
        if ($obj->save()) {
            return $this->sendSuccessResponse('出库成功');
        } else {
            return $this->sendErrorResponse(500, '出库失败');
        }
    }



    /**
     * 上报设备
     *
     * created by dale 20171023
     */
    public function reportDevAction()
    {
        $schools = XhcustInfo::find([
            'columns' => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete=0 AND iSchoolId is not null'
        ]);
        $schools = array_column($schools->toArray(), 'sSchoolName', 'iSchoolId');
        Assets::easyUIMobile();
        $this->view->pick('moblie/reportDev');
        Assets::importJs('js/moblie/reportDev.js');
        $this->view->setVars([
            'schools' => $schools,
        ]);
    }

    /**
     * 设备上报
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 20171023
     */
    public function saveDevAction()
    {
        $sDeviceNumber = $this->request->getPost('sDeviceNumber', 'string');
        $sBoxCode      = $this->request->getPost('sBoxCode','string');
        $iSchoolId     = $this->request->getPost('iSchoolId','string');
        $nowDate       = date('Y-m-d H:i:s',time());
        $resStr = '';
        if(!$sDeviceNumber || !$sBoxCode || !$iSchoolId ){
            return  $this->sendErrorResponse(500, '缺少参数');
        }

        $iSchoolId = $this->request->getPost('iSchoolId', 'string') or die('缺少参数');
        $store = XHsysDeviceStore::findFirst([
            'conditions' => 'sDeviceNumber = :sDeviceNumber: AND bDelete=0',
            'bind' => ['sDeviceNumber' => $sDeviceNumber],
        ]);

        $box = XHImsBoxIn::findFirst([
            'conditions' => 'bDelete = 0 AND sBoxCode = :sBoxCode:',
            'bind'       => ['sBoxCode' => $sBoxCode],
        ]);
        if(!$box){
            return $this->sendErrorResponse(500, '未找到箱子，请确认箱码');
        }
        $prodOut = XHImsProdOut::findFirst([
            'conditions' => 'bDelete =  0 AND sProdCode = :code:',
            'bind'       =>  ['code' => $sDeviceNumber],
        ]);
        if($prodOut){
            return $this->uploadStore($sDeviceNumber,$iSchoolId);
        }
        //如果没有出库，补出库
        $prodOut = new XHImsProdOut();
        $prodOut->iBoxId    = $box->iBoxId;
        $prodOut->iProdId   = $box->iProdId;
        $prodOut->iTypeId   = $box->iTypeId;
        $prodOut->iSchoolId = $iSchoolId;
        $prodOut->sProdCode = $sDeviceNumber;
        $prodOut->iType     = 1;

        if (!$store) {
            if(!$this->isCouldInBox($sBoxCode)){
                return $this->sendErrorResponse(500, '上报完成');
            }
            $prod = XHImsProdIn::findFirst([
                'conditions' => 'bDelete = 0 AND  sProdCode = :code:  AND iState = 1',
                'bind'       => ['code' => $sDeviceNumber]
            ]);
            if(!$prod){
                $prod = new XHImsProdIn();
            }
            $prod->iBoxId    = $box->iBoxId;
            $prod->iProdId   = $box->iProdId;
            $prod->iTypeId   = $box->iTypeId;
            $prod->sProdCode = $sDeviceNumber;
            $prod->iState    = 3;
            $prod->sRemark  .= '出库录入';
            if($prod->save()){
                $resStr .= $nowDate.'出库录入成功<br>';
            }else{
                $resStr .= $nowDate.'出库录入失败<br>';
            }
            $store = new XHsysDeviceStore();
        }else{
            $prod = XHImsProdIn::findFirst([
                'conditions' => 'bDelete = 0 AND  sProdCode = :code: AND iState = 1',
                'bind'       => ['code' => $sDeviceNumber]
            ]);
            if(!$prod){
                return $this->sendErrorResponse(500,'该物品已出库');
            }
            $prod->iState = 3;
            $prod->sRemark  .= '出库录入';
            if($prod->save()){
                $resStr .= $nowDate.'出库录入成功<br>';
            }else{
                $resStr .= $nowDate.'出库录入失败<br>';
            }
        }
        $store->assign($this->request->getPost());


        if ($store->save()) {
            if($prodOut->save()){
                $resStr .='出库记录成功<br>';
            }else{
                $resStr .='出库记录失败<br>';
            }
            if($box->iState == 1){
                $box->iLeftNum -= 1;
                if($box->iLeftNum == 0){
                    $box->iState = 2;
                }
                $box->save();
            }
            return $this->sendSuccessResponse($resStr);
        } else {
            return $this->sendErrorResponse(500, '保存失败');
        }
    }

    /**
     * 已出库的处理方式
     *
     * @param $sDeviceNumber
     * @param $iSchoolId
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20171212
     */
    public function uploadStore($sDeviceNumber,$iSchoolId){
        $store = XHsysDeviceStore::findFirst([
            'conditions' => 'sDeviceNumber = :sDeviceNumber: AND bDelete=0',
            'bind' => ['sDeviceNumber' => $sDeviceNumber],
        ]);
        if(!$store){
            $store = new XHsysDeviceStore();
        }

        $store->sDeviceNumber = $sDeviceNumber;
        $store->iSchoolId     = $iSchoolId;
        if($store->save()){
            return $this->sendSuccessResponse('上报成功');
        }else{
            return $this->sendSuccessResponse('上报失败');
        }
    }



    public function getTypeOtherAction($singleTab = false){
        $types = XHImsProdType::getProdTypeEnum();
        $arr = [];
        if($singleTab){//只要平板
            foreach ($types as $index=>$value){
                if($value == '平板'){
                    $arr[]=['id'=>$index,'text'=>$value];
                }
            }
        }else{
            foreach ($types as $index=>$value){
                if($value != '平板'){
                    $arr[]=['id'=>$index,'text'=>$value];
                }
            }
        }
        return json_encode($arr);
    }


    /**
     * 判断是否可入库
     *
     * @param $boxCode
     * @return bool
     *
     * create by dale 20171212
     */
    private function isCouldInBox($boxCode){
        $arr = [];
        $sql = "select iBoxId,iProdNum from XHIms_BoxIn where bDelete = 0 AND sBoxCode = '{$boxCode}' ";
        $data = $this->db->fetchOne($sql);
        $arr['total']   = $data['iProdNum'];
        $sql = "select count(iPInId) as nums from XHIms_ProdIn where bDelete = 0 AND  iBoxId= '{$data[0]['iBoxId']}' ";
        $data = $this->db->fetchOne($sql);
        $arr['current'] = $data['nums'];
        if(intval($arr['total'])-intval($arr['current']) == 0 ){
            return false;
        }else{
            return true;
        }
    }





}